<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-form-item label="模型设置">
            <el-button type="primary" @click="dialogVisible = true">设置算法模型</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-form-item label="诊断数据">
            <el-upload
              class="upload-demo"
              ref="upload"
              action="#"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :http-request="uploadHttpRequest"
              multiple
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="uploadFiles"
              :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只支持csv/mat格式文件</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">诊断</el-button>
        <el-button @click="resetQuery">取消</el-button>
        <!--        <el-button type="primary" @click="downloadPdf">下载</el-button>-->
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="diagnosisResultData" @selection-change="handleSelectionChange">
      <el-table-column prop="fault" label="故障率" align="center">
      </el-table-column>
      <el-table-column prop="inner" label="内圈故障率" align="center">
      </el-table-column>
      <el-table-column prop="outer" label="外圈故障率" align="center">
      </el-table-column>
      <el-table-column prop="ball" label="滚动体故障率" align="center">
      </el-table-column>
    </el-table>
    <el-card>
      <div slot="header"><span>诊断结果</span></div>
      <div class="el-table el-table--enable-row-hover el-table--medium">
        <div ref="resultEchart" style="height: 420px"/>
      </div>
    </el-card>
    <el-dialog
      title="设置算法最优模型"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose">
      <OptimizerModel></OptimizerModel>
    </el-dialog>
  </div>
</template>

<script>
  import {Diagnosis, Download} from "../../../api/bearing/diagnosis";
  import * as echarts from "echarts";
  import OptimizerModel from "./optimizedModel";

  export default {
    name: "Diagnosis",
    components: {OptimizerModel},
    data() {
      return {
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        dialogVisible: false,
        fileList: [],
        signalAnalysisType1: true,
        signalAnalysisType2: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          filtering: null,
          name: null,
          datasetName: null,
          conditionName: null,
          bearingName: null,
        },
        // 表单参数
        form: {},
        diagnosisResultData: [],
        resultEchart: null,
        // 表单校验
        rules: {}
      }
    }
    ,
    /**
     * 数据发生改变
     */

    watch: {}
    ,

    /**
     * 创建完毕
     */

    created() {
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
      // 查询所有元器件信息
      getList() {
        let formData = new FormData();
        if ("undefined" === typeof (this.form.files)) {
          this.$modal.msgError("请上传数据文件");
          return;
        }
        formData.append('files', this.form.files[0].raw);
        // 将其他数据写入json对象
        for (let key in this.form) {
          if (key !== "files") {
            formData.append(key, this.form[key])
          }
        }
        this.loading = true;
        Diagnosis(formData)
          .then(response => {
            let a = [];
            let b = response.data;
            for (let i = 0; i < response.data.length; i++) {
              if (b[i].name === "参数") {
                let p = b[i].value.split(",");
                this.diagnosisResultData = [{fault: p[0], inner: p[1], outer: p[2], ball: p[3]}]
              } else {
                a.push({name: b[i].name, value: b[i].value})
              }
            }
            this.resultEchart = echarts.init(this.$refs.resultEchart, "macarons");
            this.resultEchart.setOption({
              tooltip: {
                trigger: "item",
                formatter: "{a} <br/>{b} : {c} ({d}%)",
              },
              series: [
                {
                  name: "命令",
                  type: "pie",
                  roseType: "radius",
                  data: a,
                  animationEasing: "cubicInOut",
                  animationDuration: 1000,
                }
              ]
            });
            this.loading = false
            this.handleDownload();
          }).catch(() => {
          this.loading = false
        });
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      uploadHttpRequest(data) {
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      uploadFiles(item, fileList) {
        this.form.files = fileList
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.form.filtering = null;
        this.fileList = [];
        this.form.files = undefined;
        this.loading = true;
        this.Data = [];
        this.loading = false;
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.bid)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
      },
      changeAnalysisType1(type) {
        this.signalAnalysisType2 = !type
      },
      changeAnalysisType2(type) {
        this.signalAnalysisType1 = !type
      },
      handleDownload() {
        Download().then(res => {
          const blob = new Blob([res], {type: 'application/csv'});
          const url = URL.createObjectURL(blob);
          let anchor = document.createElement("a");
          //设置下载的文件名
          anchor.download = `result_${new Date().getTime()}.csv`;
          anchor.href = url;
          anchor.click();
        })
      }
    }
  }
</script>
